package com.chaochis.springboottestdemo.config.redisConfig;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis 配置
 */
@Configuration
public class RedisConfig {
   /* *//**//**//**//**
   * 使用的fastJson配置的<string, object>模板，不能保存类信息
   *
   * @param redisConnectionFactory
   * @return
   *//**//**//**/
  @Bean(name = "redisFastJsonTemplate")
  public RedisTemplate<String, Object> redisFastJsonTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> redisFastJsonTemplate = new RedisTemplate<>();
    redisFastJsonTemplate.setConnectionFactory(redisConnectionFactory);
    FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
    // 全局开启AutoType，不建议使用
    // ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
    // 建议使用这种方式，小范围指定白名单
    ParserConfig.getGlobalInstance().addAccept("com.chaochis.springboottestdemo");
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    // 设置值（value）的序列化采用FastJsonRedisSerializer。
    redisFastJsonTemplate.setValueSerializer(fastJsonRedisSerializer);
    redisFastJsonTemplate.setHashValueSerializer(fastJsonRedisSerializer);
    // 设置键（key）的序列化采用StringRedisSerializer。
    redisFastJsonTemplate.setKeySerializer(stringRedisSerializer);
    redisFastJsonTemplate.setHashKeySerializer(stringRedisSerializer);

    redisFastJsonTemplate.afterPropertiesSet();
    return redisFastJsonTemplate;
  }

  @Bean(name = "redisJackJsonTemplate")
  public RedisTemplate<String, Object> redisJackJsonTemplate(RedisConnectionFactory redisConnectionFactory) {
    RedisTemplate<String, Object> redisJackJsonTemplate = new RedisTemplate<>();
    redisJackJsonTemplate.setConnectionFactory(redisConnectionFactory);
    ParserConfig.getGlobalInstance().addAccept("com.chaochis.springboottestdemo");

    // 自定义的string序列化器和fastjson序列化器
    StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

    // jackson 序列化器
    GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

    // kv 序列化
    redisJackJsonTemplate.setKeySerializer(stringRedisSerializer);
    redisJackJsonTemplate.setValueSerializer(jsonRedisSerializer);

    // hash 序列化
    redisJackJsonTemplate.setHashKeySerializer(stringRedisSerializer);
    redisJackJsonTemplate.setHashValueSerializer(jsonRedisSerializer);

    redisJackJsonTemplate.afterPropertiesSet();
    return redisJackJsonTemplate;
  }
}
